import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:syn_4s/core/extension/build_context_extension.dart';
import 'package:syn_4s/core/extension/int_extension.dart';
import 'package:syn_4s/core/model/user_tag_model.dart';

import '../../core/constants/event_code.dart';
import '../../core/constants/sp_key.dart';
import '../../core/constants/tag_code.dart';
import '../../core/router/router.dart';
import '../../core/utils/event_bus.dart';
import '../../core/utils/sp_utils.dart';
import '../shared/app_theme.dart';

class MainDrawer extends StatelessWidget {
  const MainDrawer({super.key});

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<dynamic>(
        future: SPUtils.get(keyTag),
        builder: (ctx, snapshot) {
          return Drawer(
            width: 280.px,
            backgroundColor: Colors.orange,
            child: Container(
              padding: EdgeInsets.only(top: 60.px, bottom: 16.px),
              decoration: const BoxDecoration(
                  borderRadius: BorderRadius.zero,
                  gradient: LinearGradient(colors: [
                    AppTheme.drawerStartColor,
                    AppTheme.drawerEndColor
                  ])),
              child: buildDrawerChild(context, snapshot),
            ),
          );
        });
  }

  Widget buildDrawerChild(BuildContext context, dynamic snapshot) {
    return Column(
      children: [
        buildMenu(context, snapshot),
        const Spacer(),
        Padding(
          padding: EdgeInsets.symmetric(horizontal: 16.px),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              InkWell(
                  onTap: () {
                    Get.back();
                    if (MyRouter.getCurrentRoute(context) !=
                        MyRouter.settingRoute) {
                      Get.toNamed(MyRouter.settingRoute);
                      // Get.toNamed(MyRouter.surveillanceRoute);
                    }
                  },
                  child: Row(
                    children: [
                      const Icon(
                        Icons.settings,
                        color: Colors.white,
                      ),
                      buildBigText(context.l10n.setting)
                    ],
                  )),
              const Spacer(),
              buildBigText("V1.0.0")
            ],
          ),
        )
      ],
    );
  }

  Widget buildMenu(BuildContext context, dynamic snapshot) {
    if (snapshot.connectionState == ConnectionState.waiting) {
      return const Center(
        child: CircularProgressIndicator(), // 数据加载时显示进度指示器
      );
    } else if (snapshot.hasError) {
      return Container();
    } else {
      if (snapshot.data == null || snapshot.data.isEmpty) {
        return Container();
      }
      List<UserTagModel> tags = (jsonDecode(snapshot.data ?? "") as List)
          .map((e) => UserTagModel.fromJson(e))
          .toList();
      UserTagModel? statusModel;
      UserTagModel? realModel;
      UserTagModel? cctvModel;
      List<UserTagModel> statusList = [];
      for (var value in tags) {
        if (value.code == codeStatus) {
          statusModel = value;
        } else if (value.code == codeRealLocation) {
          realModel = value;
        } else if (value.code == codeSurveillance) {
          cctvModel = value;
        } else {
          statusList.add(value);
        }
      }
      return Column(
        children: [
          Offstage(
            offstage: statusModel == null,
            child: ExpansionTile(
                collapsedIconColor: Colors.white,
                iconColor: Colors.white,
                title: buildBigText(
                    statusModel?.name ?? context.l10n.device_status),
                children: List.generate(statusList.length + 1, (index) {
                  if (index == 0) {
                    return buildChildItem(context, context.l10n.all, eventAll);
                  } else {
                    String defaultName = "";
                    int eventCode = 0;
                    switch (statusList[index - 1].code) {
                      case codePermitToWork:
                        defaultName = context.l10n.permit_to_work;
                        eventCode = eventPermitToWork;
                        break;
                      case codeSafetyTraining:
                        defaultName = context.l10n.safety_training;
                        eventCode = eventSafetyTraining;
                        break;
                      case codeGas:
                        defaultName = context.l10n.gas_monitoring;
                        eventCode = eventGasMonitoring;
                        break;
                      case codeWatch:
                        defaultName = context.l10n.smart_watch;
                        eventCode = eventSmartWatch;
                        break;
                      case codeLock:
                        defaultName = context.l10n.smart_lock;
                        eventCode = eventSmartLock;
                        break;
                      case codeTracking:
                        defaultName = context.l10n.tracking_sys;
                        eventCode = eventTrackingSystem;
                        break;
                      case code360:
                        defaultName = context.l10n.plant_360;
                        eventCode = event360;
                        break;
                      case codeAlert:
                        defaultName = context.l10n.alert;
                        eventCode = eventAlert;
                        break;
                      case codeUnSafeAct:
                        defaultName = context.l10n.unsafe_act;
                        eventCode = eventUnsafeAct;
                        break;
                    }
                    return buildChildItem(context,
                        statusList[index - 1].name ?? defaultName, eventCode);
                  }
                })),
          ),
          Offstage(
            offstage: realModel == null,
            child: ListTile(
              onTap: () {},
              title:
                  buildBigText(realModel?.name ?? context.l10n.real_location),
            ),
          ),
          Offstage(
            offstage: cctvModel == null,
            child: ListTile(
              onTap: () {
                Get.toNamed(MyRouter.surveillanceRoute);
              },
              title: buildBigText(cctvModel?.name ?? context.l10n.surveillance),
            ),
          )
        ],
      );
    }
  }

  Widget buildChildItem(BuildContext context, String data, int value) {
    return InkWell(
      onTap: () {
        Get.back();
        if (MyRouter.getCurrentRoute(context) != MyRouter.mainRoute) {
          Get.offAllNamed(MyRouter.mainRoute);
        }
        eventBus.fire({eventType: eventScroll, eventValue: value});
      },
      child: Container(
        alignment: Alignment.centerLeft,
        padding: EdgeInsets.only(left: 40.px, right: 8.px, bottom: 12.px),
        child: buildWhiteText(data),
      ),
    );
  }

  Widget buildBigText(String data) {
    return buildWhiteText(data, fontSize: 16);
  }

  Widget buildWhiteText(String data, {double? fontSize}) {
    return Text(
      data,
      style: TextStyle(color: Colors.white, fontSize: fontSize ?? 14),
    );
  }
}
